using UnityEngine;

using System.Collections;

public class GodRay : PostEffectsBase
{
    public Shader godRayShader;
    private Material godRayMaterial = null;
    public Material material{
        get {
            godRayMaterial = CheckShaderAndCreateMaterial(godRayShader, godRayMaterial);
            return godRayMaterial;
        }
    }

    [Range(1, 8)]
    public int downSample = 2;

    [Range(0.0f,1.0f)]
    public float luminanceThreshold = 0.6f;

    [Range(0.0f, 0.1f)]
    public float blurFactor = 0.5f;

    [Range(1, 10)]
    public int blurNum = 5;

    [Range(0, 10)]
    public int blurIteration = 5;

    [Range(0.0f, 1f)]
    public float lightFactor = 0.5f;

    public Vector2 blurCenter = new Vector2(0.5f, 0.5f);

    void OnRenderImage (RenderTexture src, RenderTexture dest) {
        if (material != null) {
            material.SetFloat("_LuminanceThreshold", luminanceThreshold);

            int rtW = src.width/downSample;
            int rtH = src.height/downSample;

            RenderTexture buffer0 = RenderTexture.GetTemporary(rtW, rtH, 0);
            buffer0.filterMode = FilterMode.Bilinear;

            //提取 亮光
            Graphics.Blit(src, buffer0, material, 0);

            material.SetFloat("_blurFactor", blurFactor);
            material.SetVector("_blurCenter", blurCenter);
            material.SetInt("_blurNum", blurNum);

            for(int i=0; i< blurIteration; i++){

                RenderTexture buffer1 = RenderTexture.GetTemporary(rtW, rtH, 0);
                //径向发散亮光
                Graphics.Blit(buffer0, buffer1, material, 1);

                RenderTexture.ReleaseTemporary(buffer0);
                buffer0 = buffer1;
            }
            
            material.SetTexture("_GodRay", buffer0);
            material.SetFloat("_lightFactor", lightFactor);
            Graphics.Blit(src, dest, material, 2);
            RenderTexture.ReleaseTemporary(buffer0);

            //Graphics.Blit(buffer0, dest);
        }
        else{
            Graphics.Blit(src, dest);
        }
    }

}
